package instan_srv

import (
	"encoding/json"
	"fmt"
	apis2 "gluenet/pkg/apis"
	"gluenet/pkg/meta"
	glue2 "gluenet/pkg/platform/glue"
	"gopkg.in/yaml.v3"
	"strings"
)

func AppServiceGet(ctx *apis2.GlueContext) {
	var (
		err     error
		guid    string
		service string
	)
	guid = ctx.WebContext.URLParam("guid")
	service = ctx.WebContext.URLParam("service")

	//var ins []meta.Instance
	//if err = orm.InstanceGet(ctx.DataBase, guid, &ins); err != nil || len(ins) == 0 {
	//	ctx.Logger.Errorf("cant't find instance %v", err)
	//	ctx.WebContext.JSON(apis.ResponseReqErr(fmt.Errorf("cant't find instance %v", err), nil))
	//	return
	//}
	var ins *meta.Instance
	if err = ctx.DataBase.InstanceGet(guid, &ins); err != nil {
		ctx.Logger.Errorf("cant't find instance %v", err)
		ctx.WebContext.JSON(apis2.ResponseReqErr(fmt.Errorf("cant't find instance %v", err), nil))
		return
	}

	labels := strings.Split(ins.Label, ".")
	if labels[1] != apis2.ModuleDefault || labels[3] != apis2.KindApplication {
		ctx.WebContext.JSON(apis2.ResponseOK(nil))
		return
	}

	var gin glue2.Instance
	if err = json.Unmarshal([]byte(ins.InstanceValue), &gin); err != nil {
		ctx.Logger.Errorf("unmarshall %v", err)
		ctx.WebContext.JSON(apis2.ResponseReqErr(fmt.Errorf("unmarshall %v", err), nil))
		return
	}

	var container glue2.Containers
	if err = yaml.Unmarshal([]byte(gin.InstanceYaml), &container); err != nil {
		ctx.Logger.Errorf("unmarshall yaml %v", err)
		ctx.WebContext.JSON(apis2.ResponseReqErr(fmt.Errorf("unmarshall yaml %v", err), nil))
		return
	}

	c, ok := container.Containers[service]
	if !ok {
		ctx.WebContext.JSON(apis2.ResponseOK(nil))
		return
	}
	if c.Service == "" {
		ctx.WebContext.JSON(apis2.ResponseOK(nil))
		return
	}
	ctx.WebContext.JSON(apis2.ResponseOK(c.Service))
}
